package core

import (
	"biliMiddleware/global"
	"biliMiddleware/model"
	"bytes"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	"strings"
	"sync"

	"github.com/tidwall/gjson"
)

var Token string

func init() {
	ServiceLogin()
}

// ServiceLogin 登录
func ServiceLogin() {
	data := map[string]string{"username": "admin", "password": "fjiabinc"}
	b, _ := json.Marshal(data)
	URL := fmt.Sprintf("%v/user/login", global.Config.Service.Host)
	resp, err := http.Post(URL, "", strings.NewReader(string(b)))
	if err != nil {
		return
	}
	body, _ := ioutil.ReadAll(resp.Body)
	Token = gjson.Get(string(body), "data.token").String()
	resp.Body.Close()
}

// ServiceGetTaskList 获取任务列表
func ServiceGetTaskList(roomStatus string) (taskList []model.Task) {
	URL := fmt.Sprintf("%v/task", global.Config.Service.Host)
	req, err := http.NewRequest("GET", URL, nil)
	if err != nil {
		return []model.Task{}
	}
	req.Header.Set("token", Token)
	param := req.URL.Query()
	// 不分页获取全部
	param.Set("all", "1")
	// 筛选条件 开播状态为开播
	if roomStatus != "" {
		param.Set("room_status", "1")
	}
	req.URL.RawQuery = param.Encode()
	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		return []model.Task{}
	}
	defer resp.Body.Close()
	body, _ := ioutil.ReadAll(resp.Body)
	if resp.StatusCode == 200 {
		code := gjson.Get(string(body), "code").Int()
		if code != 0 {
			msg := gjson.Get(string(body), "msg").String()
			if msg == "未登录或非法访问" {
				ServiceLogin()
				ServiceGetTaskList(roomStatus)
			}
		} else {
			data := gjson.Get(string(body), "data.task").String()
			_ = json.Unmarshal([]byte(data), &taskList)
			return taskList
		}
	} else {
		fmt.Println("服务器出错")
	}
	return []model.Task{}
}

// ServicePutTask 更新房间状态
func ServicePutTask(Data model.Task, wg *sync.WaitGroup) {
	defer wg.Done()
	URL := fmt.Sprintf("%v/task", global.Config.Service.Host)
	b, _ := json.Marshal(Data)
	req, _ := http.NewRequest("PUT", URL, bytes.NewReader(b))
	req.Header.Set("token", Token)
	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		return
	}
	defer resp.Body.Close()
}

// ServiceGetProgramHash 获取客户端最新的hash值
func ServiceGetProgramHash() string {
	URL := fmt.Sprintf("%v/upload/program_hash", global.Config.Service.Host)
	req, err := http.NewRequest("GET", URL, nil)
	if err != nil {
		return ""
	}
	req.Header.Set("token", Token)
	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		return ""
	}
	defer resp.Body.Close()
	readAll, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return ""
	}
	hash := gjson.Get(string(readAll), "data.hash").String()
	return hash
}
